import java.util.*;

public class HuffmanCodeDemo {
    public static void main(String[] args) {
        String context = "i like like like java do you like a java";
        byte[] contextByte = context.getBytes();
        List<Node> nodes = getNode(contextByte);
        Node huffmanTreeRoot = creatHuffmanTree(nodes);
        System.out.println("哈夫曼树:" + huffmanTreeRoot);
        System.out.println("前序遍历");
        huffmanTreeRoot.preOrder();
    }

    public static List<Node> getNode(byte[] Byte){
        List<Node> nodes = new ArrayList<Node>();
        //key为coutext中的字符，value为每个字符的出现的次数
        Map<Byte,Integer> counts = new HashMap<>();

        for(byte b : Byte){
            Integer count = counts.get(b);
            if(count == null){
                counts.put(b,1);
            }else{
                counts.put(b,count + 1);
            }
        }

        //遍历map
        for(Map.Entry<Byte,Integer> entry : counts.entrySet()){
            nodes.add(new Node(entry.getKey(),entry.getValue()));
        }
        return nodes;
    }

    private static void preOrder(Node root){
        if(root != null){
            preOrder(root);
        }else{
            System.out.println("哈夫曼树为空");
        }
    }

    private static Node creatHuffmanTree(List<Node> nodes){
        while(nodes.size() > 1){
            Collections.sort(nodes);

            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);

            Node parent = new Node(null,leftNode.wight + rightNode.wight);
            parent.left = leftNode;
            parent.right = rightNode;

            nodes.remove(leftNode);
            nodes.remove(rightNode);

            nodes.add(parent);
        }
        return nodes.get(0);
    }
}

class Node implements Comparable<Node>{
    Byte data;
    int wight;
    Node left;
    Node right;

        public Node(Byte data, int wight) {
        this.data = data;
        this.wight = wight;
    }

    @Override
    public String toString() {
        return "Node{" +
                "data=" + data +
                ", wight=" + wight +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        return this.wight - o.wight;
    }

    public void preOrder(){
        System.out.println(this);

        if(this.left != null){
            this.left.preOrder();
        }

        if(this.right != null){
            this.right.preOrder();
        }
    }
}
